// pages/sufferer/orbit/orbit.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    provinces:[],
    cities:{},
    province:"点击选择城市",
    city:"",
    multiArray: [[],[]],
    multiIndex: [0, 0],
    dates:[],
    my:{},
    myModal: false,
    suffererModel: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation']) {
         wx.getLocation({
             success(res){
                 that.setData({
                   lat:res.latitude,
                   lng:res.longitude
                 });
             }
         })
        }else {
            wx.openSetting({
                success(res) {
                    if (res.authSetting["scope.userLocation"]) {
                         wx.getLocation({
                            success(res){
                              that.setData({
                                lat:res.latitude,
                                lng:res.longitude
                              });
                            }
                        })
                    }
                }
            })
        }
      }
    })

    wx.cloud.callFunction({
      name: 'getCities',
      data: {
      },
      success: function (res) {
          var r = res.result.data;
          var provinces = [];
          var cities={};
          for (var i in r){
              provinces.push(r[i]._id);
              cities[r[i]._id]=r[i].citys;
          }
          that.setData({
            cities:cities,
            provinces:provinces,
            multiArray:[provinces,cities[provinces[0]]],
            multiIndex: [0, 0],
          });
      },
      fail: err => {
        console.error(err);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        pageCur: 'orbit',
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title:"疫轨迹，了解感染者出行活动，发现自身感染风险",
      imageUrl:"/images/share.png",
      path:"/pages/sufferer/travel/travel",
    }
  },

  MultiColumnChange(e) {
    var that = this;
    let multiArray =[that.data.multiArray[0],[]]
    if (e.detail.column == 0){
      multiArray[1]=that.data.cities[that.data.provinces[e.detail.value]];
      that.setData({
        multiArray:multiArray
      });
    }
  },

  MultiChange(e) {
    var that =this;
    var city = that.data.multiArray[1][e.detail.value[1]];
    var province = that.data.multiArray[0][e.detail.value[0]];

    that.setData({
      province:province,
      city:city,
      multiIndex: e.detail.value
    });
    wx.showLoading({
      title: '查询中',
    });
    wx.cloud.callFunction({
      name: 'getSufferOrbits',
      data: {
        city:city
      },
      success: function (res) {
        wx.hideLoading();
        var resultData = res.result.data;
        var resultMyData = res.result.my;
        var data = {};
        var dates = [];
        var my = {};
        //返回的结果是按date降序排列
        for (var i = 0, len = resultData.length; i < len; i++) {
          if (!(resultData[i]["date"] in data)) {
            data[resultData[i]["date"]] = [];
            dates.push(resultData[i]["date"]);
          }
          data[resultData[i]["date"]].push(resultData[i]);
        }
        for (var i = 0, len = resultMyData.length; i < len; i++) {
          if (resultMyData[i]["date"] in data) {
            if(!(resultMyData[i]["date"] in my)){
              my[resultMyData[i]["date"]] = [];
            }
            my[resultMyData[i]["date"]].push(resultMyData[i]);
          }
        }

        that.setData({
          my:my,
          data: data,
          dates: dates,
          lng:data[dates[0]][0].location.coordinates[0],
          lat: data[dates[0]][0].location.coordinates[1],
        });
        
          that.changeDate(dates[0]);

      },
      fail: err => {
        wx.hideLoading();
        wx.showToast({
            icon: 'none',
            title: '暂无数据'
        });
      }
    });
  },


  changeDate: function( toDate){
    var that = this;
    var markers = [];
    var data = that.data["data"][toDate];
    var todaySufferer = {};
    var todayMy ={};
    for (var i = 0, len = data.length; i < len; i++) {
      var marker = {}
      marker["id"] = i+1;
      marker["latitude"] = data[i].location.coordinates[1];
      marker["longitude"] = data[i].location.coordinates[0];
      marker["iconPath"]="/images/mark2.png";
      marker["callout"]	={
              content:"患者",
              color:"#fff",
              bgColor:"#e54d42",
              display:'ALWAYS',
              borderRadius:5,
              padding:3,
            };
      markers.push(marker);
      todaySufferer[i+1]=data[i];
    }
    if(toDate in that.data["my"]){
      
      let my = that.data["my"][toDate];
      for (var i = 0, len = my.length; i < len; i++) {
        var marker = {}
        marker["id"] = (i+1)*-1;
        marker["latitude"] = my[i].location.coordinates[1];
        marker["longitude"] = my[i].location.coordinates[0];
        marker["iconPath"]="/images/mark1.png";
        marker["callout"]	={
                content:"我",
                color:"#fff",
                bgColor:"#0081ff",
                display:'ALWAYS',
                borderRadius:5,
                padding:3,
              };
        markers.push(marker);
        todayMy[(i+1)*-1]=my[i];
      }
    }

    that.setData({
      todaySufferer:todaySufferer,
      todayMy:todayMy,
      markers: markers,
      showdate: toDate,
    });
  },

  bindPickerDateChange: function (e) {
    var that = this;
    var index = e.detail.value
    that.changeDate(that.data["dates"][index]);
  },


  copyText: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              icon: 'none',
              title: '复制成功,请到浏览器查看信息源'
            })
          }
        })
      }
    })
  },

  showModal(e) {
    var that =this;
    var id = e.markerId;
    if (id<0){
      that.setData({
        showData:that.data.todayMy[id],
        myModal: true,
      });
    }else{
      that.setData({
        showData:that.data.todaySufferer[id],
        suffererModal: true
      });
    }
  },


  hideModal(e) {
    var that = this;
    that.setData({
      myModal: false,
      suffererModal:false,
    })
  },

})